package spitfire.ksim.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import spitfire.ksim.node.KSensor;
import spitfire.ksim.node.KSensorNode;
import spitfire.ksim.simulator.KSimulator;

/**
 * 
 */
public class KSensorDataPanel extends Plotter2DPanel {
	
	private static final long serialVersionUID = 941369858271904290L;
	private KSimulator simulator;
	private KSensor sensor;
	private KSensorNode sNode;

	public KSensorDataPanel(KSensorNode sNode, KSensor sensor, KSimulator simulator) {
		super();
		this.simulator = simulator;
		this.sensor = sensor;
		this.sNode = sNode;
		List<Long> timeList = sensor.getTimeStampList();
		List<Double> dataList = sensor.getDataList();
		setData(timeList, dataList);
		if (dataList.size() != 0) {
			setDataWindowBottom(Collections.min(dataList));
			setDataWindowTop(Collections.max(dataList));
		}
		
		setBackground(Color.WHITE);
		setPreferredSize(new Dimension(300, 100));
		setyAxisLoc(2);
		setAxisStatus(Y_AXIS_ONLY);
		setRuler(true);
		setXLabelFormat(DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
				DateFormat.MEDIUM, Locale.GERMANY));
	}

	@Override 
	public void paintComponent(Graphics g) {
		if (sensor.isPowerOn()) {
			setBackground(Color.WHITE);
			long simTime = simulator.getSimTime();
			long timeWindow = 1;
			long timeWindowOption = sNode.getTimeWindowOption();
			
			if(timeWindowOption == 1){
				timeWindow = KSensorNode.commonTimeWindow;
			} else {
				timeWindow = sNode.getTimeWindow();
			}
			
			int fromIndex = Arrays.binarySearch(getXSequence(), simTime - timeWindow);
			int toIndex = Arrays.binarySearch(getXSequence(), simTime);
			if (fromIndex < 0) {
				// not found, convert to insertion point. @see Collections.binarySearch; 
				fromIndex = -fromIndex - 1;
			}
			if (toIndex < 0) {
				toIndex = -toIndex - 1;
			}
			setPlotInterval(fromIndex, toIndex);
			setDataWindowLeft(simTime - timeWindow);
			setDataWindowRight(simTime);
		} else {
			setBackground(Color.LIGHT_GRAY);
		}
		super.paintComponent(g);
	}
}
